
package com.neo.tiny.admin.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.admin.entity.sys.SysDictItem;
import com.neo.tiny.admin.mapper.sys.SysDictItemMapper;
import com.neo.tiny.admin.service.sys.SysDictItemService;
import com.neo.tiny.common.constant.ErrorCodeConstants;
import com.neo.tiny.common.exception.WebApiException;
import com.neo.tiny.query.LambdaQueryWrapperBase;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 字典数据
 *
 * @author yqz
 * @date 2022-09-03 17:45:11
 */
@Service
@AllArgsConstructor
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService {

    private final SysDictItemMapper dictItemMapper;

    @Override
    public void validDictDatas(String dictType, Collection<String> values) {

        if (CollUtil.isEmpty(values)) {
            return;
        }

        List<SysDictItem> itemList = dictItemMapper.selectList(new LambdaQueryWrapperBase<SysDictItem>()
                .eq(SysDictItem::getDictType, dictType)
                .in(SysDictItem::getDictValue, values));

        Map<String, SysDictItem> dictItemMap = itemList.stream()
                .collect(Collectors.toMap(SysDictItem::getDictValue, Function.identity(), (key1, key2) -> key1));

        values.forEach(value -> {
            SysDictItem item = dictItemMap.get(value);
            if (Objects.isNull(item)) {
                throw new WebApiException(ErrorCodeConstants.DICT_DATA_NOT_EXISTS);
            }
        });
    }
}
